<?php

namespace App\Kuafu\Pay\Logging;

use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class PayCustomLogger
{
    public function __invoke(array $config)
    {
        $monolog = new Logger($config['driver']);
        $format  = "[%extra.datetime%] %level_name% [%extra.path%] [%extra.method%] [%extra.params%] [%extra.ip%] [%extra.real_ip%] : %message% %context%\n";

        $monolog->pushHandler(
            $logHandler = new StreamHandler(
                $config['path'] . "/pay_" . date("Y-m-d") . ".log", $config['level']
            )
        );
        $logHandler->setFormatter(
            $formatter = new LineFormatter($format, null, true, true)
        );
        $request = request();
        $logHandler->pushProcessor(function ($record) use ($request) {
            $record['extra']['path']    = $request->path();
            $record['extra']['method']  = $request->method();
            $record['extra']['ip']      = $request->ip();
            $record['extra']['real_ip'] = $request->header("x-forwarded-for");
            $record['extra']['params']  = $request->all();
//            $record['extra']['uid'] = $app_cp->user_id??0;
            $record['extra']['datetime'] = date("Y-m-d H:i:s") . "," . array_sum(explode(" ", microtime()));
            return $record;
        });
        $formatter->includeStackTraces();
        return $monolog;
    }
}
